package com.x.erp.service;

import java.util.List;
import com.x.erp.util.CodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.annotation.Service;
import com.x.erp.dao.MarketDao;
import com.x.erp.model.Market;
import com.x.erp.rpc.MarketRpcService;
import com.x.framework.exception.BusinessException;
import com.x.framework.exception.ExceptionCode;
import com.x.framework.service.BaseService;

@Component
@Service(interfaceName = "com.x.erp.rpc.MarketRpcService", timeout = 60000)
public class MarketService extends BaseService implements MarketRpcService {

	@Autowired
	private MarketDao marketDao;

	@Override
	public List<Market> selectMarketList(Market market) {
		try {
			return marketDao.selectMarketList(market);
		} catch (Exception e) {
			throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
		}
	}

	@Override
	public int selectMarketNum(Market market) {
		try {
			return marketDao.selectMarketNum(market);
		} catch (Exception e) {
			throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
		}
	}

	@Override
	public Market insertMarket(Market market) {
		try {
			String marketParentId = market.getMarketParentId();
			Market parentMarket = new Market();
			parentMarket.setMarketId(marketParentId);
			List<Market> parentMarketList = marketDao.selectMarketList(parentMarket);
			String parentMarketCode = null;
			if (parentMarketList.size() > 0) {
				parentMarket = parentMarketList.get(0);
				parentMarketCode = parentMarket.getMarketCode();
			}
			String maxCode = marketDao.selectMaxCode(marketParentId);
			String marketCode = CodeUtil.getCode(parentMarketCode, maxCode);
			market.setMarketCode(marketCode);
			market.setMarketCreateTime(this.getDate(0));
			market.setMarketUpdateTime(this.getDate(0));
			return this.insert(market);
		} catch (Exception e) {
			throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
		}
	}

	@Override
	public void updateMarket(Market market) {
		try {
			market.setMarketUpdateTime(this.getDate(0));
			this.update(market);
		} catch (Exception e) {
			throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
		}
	}

}
